package market

import (
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/market"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/market/outbound_task"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type ByCallBackController struct {
	controller.BaseController
	outboundTaskService outbound_task.OutboundTaskServiceIface
}

// NewByCallBackController 百应回调接口
func NewByCallBackController(
	outboundTaskService outbound_task.OutboundTaskServiceIface,
) *ByCallBackController {
	return &ByCallBackController{
		outboundTaskService: outboundTaskService,
	}
}

func (c *ByCallBackController) RegisterRouter(g *gin.RouterGroup) {
	// 百应回调
	g.POST("callback", c.callback)
}

func (c *ByCallBackController) callback(ctx *gin.Context) {
	var req dto.BaiYingCallBackRequest
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(req, err))
		return
	}

	if req.Data == nil || req.Data.Data == nil || req.Data.Data.CallInstance == nil {
		ctx.String(0, "fail")
		return
	}

	tenantCode, err := utils.GetTenantCodeForBy(ctx, req.Data.Data.CallInstance.CompanyId)
	if err != nil || tenantCode == "" {
		ctx.String(0, "fail")
		return
	}
	ctx.Set(authorize.TENANT_CODE_KEY, tenantCode)
	if req.Data == nil {
		ctx.String(0, "fail")
		return
	}
	err = c.outboundTaskService.HandleOutboundTaskCallback(ctx, req.Data.Data)
	if err != nil {
		stark.Logger.Infof(ctx, "callback HandleOutboundTaskCallback req:%+v, err:%s", req, err)
		ctx.String(0, "fail")
		return
	}

	ctx.String(0, "success")
}
